package com.wxblockchain.wxbasemodule.utils;

import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.wxblockchain.wxbasemodule.PermissionListener;
import com.wxblockchain.wxbasemodule.base.BaseActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;

public class PermissionUtil {
    public static void reqPermissions(WeakReference<BaseActivity> context, String[] permissions, PermissionListener listener) {
        if (permissions == null || context == null || context.get() == null || listener == null) {
            LogUtil.d("");
            return;    
        }

        ArrayList<String> requestPermissionList = new ArrayList<>();
        for (String permission : Arrays.asList(permissions)) {
            if (ContextCompat.checkSelfPermission(context.get(), permission) != PackageManager.PERMISSION_GRANTED) {
                requestPermissionList.add(permission);
            }
        }

        if (!requestPermissionList.isEmpty()) {
            ActivityCompat.requestPermissions(context.get(), requestPermissionList.toArray(new String[requestPermissionList.size()]), 1);
        } else {
            listener.onGranted();
        }
    }
}
